package com.zbkj.common.config;

import java.util.regex.Pattern;

public class AdvancedNumberFormatter {

    /**
     * 去除数字字符串中多余的前导零（保留符号）
     * @param number 输入的数字字符串（如 "-04.75", "+04.75", "012", "0", "1", "-00.12"）
     * @return 格式化后的数字字符串（如 "-4.75", "+4.75", "12", "0", "1", "-0.12"）
     */
    public static String removeLeadingZeros(String number) {
        if (number == null || number.isEmpty()) {
            return number;
        }

        // 处理纯0的情况（如 "0", "00", "-0", "+0", "-00.00"）
        if (isAllZeros(number)) {
            return number.contains("-") ? "-0" :
                    number.contains("+") ? "+0" : "0";
        }

        // 处理特殊情况：-00.12 → -0.12
        if (number.matches("[+-]0+\\.\\d+")) {
            return number.charAt(0) + "0." + number.split("\\.")[1];
        }

        // 正则表达式处理通用情况
        Pattern pattern = Pattern.compile("([+-]?)(0*)([1-9]\\d*)(\\.\\d+)?");
        java.util.regex.Matcher matcher = pattern.matcher(number);

        if (matcher.matches()) {
            String sign = matcher.group(1);  // 捕获符号
            String integerPart = matcher.group(3);  // 捕获非零整数部分
            String decimalPart = matcher.group(4);  // 捕获小数部分

            return sign + integerPart + (decimalPart != null ? decimalPart : "");
        }

        // 无法识别的格式返回原样
        return number;
    }

    private static boolean isAllZeros(String number) {
        String num = number.replaceAll("[+-]", "");
        return num.matches("0+\\.?0*");
    }

    // 测试用例
    public static void main(String[] args) {
        String[] testCases = {
                "-04.75", "+04.75", "04.75",
                "-00.12", "+00.34", "00.56",
                "-00.00", "+00.00", "000.00",
                "012", "001", "0001",
                "0", "00", "-0", "+0",
                "1", "01", "+01", "-01",
                "abc", "12.34.56", "-"
        };

        for (String test : testCases) {
            System.out.printf("输入: %-8s → 输出: %s%n",
                    test, removeLeadingZeros(test));
        }
    }
}